﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SARS.Biz;
using SARS.Entity;


namespace SARS.Course.Group
{
    public partial class CreateGroup : Page
    {
        private readonly GroupBO groupBiz = new GroupBO();
		private readonly UserBO userBiz = new UserBO();

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetNoStore();
            if (Session["Roles"] == null || RoleType.Coordinator != (RoleType)Session["Roles"])
            {
                Response.Write("<script language='javascript'>window.alert('Your role is not allow to access this page.');" +
                               "window.location='../../Account/Login.aspx';</script>");

            }
            else
            {
                if (!IsPostBack)
                {
                    Session["CHECKED_ITEMS"] = null;
                    BindStudentGridViewData();
                }    
            }
            
        }

        protected void btCreate_Click(object sender, EventArgs e)
        {
            SaveCheckedValues();
            List<string> checkedTutor = (List<string>)Session["CHECKED_ITEMS"];

            //TODO: Put those code below into transaction
            //Create Data for Group
            int newGroupId = groupBiz.CreateGroup(txtGroupName.Text, ucProgramCourse.SelectedCourseValue);
            //Assign Tutor to Group
            foreach (string tutor in checkedTutor)
            {
                groupBiz.AssignGroupTutor(newGroupId, Int32.Parse(tutor));    
            }
            
            
            //Get the current loggedin coordinator
            //CoordinatorEntity coordinator = (CoordinatorEntity)userBiz.RetrieveUserByUserName(Page.User.Identity.Name);
            //groupBiz.AssignStudentsIntoGroup(newGroupId, coordinator.UserID, checkedStudent);

            Response.Redirect("GroupDetails.aspx?gid="+newGroupId);
        }

        private void BindStudentGridViewData()
        {
            gvTutorList.DataSource = userBiz.RetrieveUserByRoleId((int)RoleType.Tutor);
            gvTutorList.DataBind();
        }

        protected void gvTutorList_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            SaveCheckedValues();
            gvTutorList.PageIndex = e.NewPageIndex;
            BindStudentGridViewData();
            PopulateCheckedValues();
        }

        //This method is used to populate the saved checkbox values
        private void PopulateCheckedValues()
        {
            List<string> checkedTutor = (List<string>)Session["CHECKED_ITEMS"];
            if (checkedTutor != null && checkedTutor.Count > 0)
            {
                foreach (GridViewRow gvrow in gvTutorList.Rows)
                {
                    string index = gvTutorList.DataKeys[gvrow.RowIndex].Value.ToString();
                    if (checkedTutor.Contains(index))
                    {
                        CheckBox myCheckBox = (CheckBox)gvrow.FindControl("cbSelect");
                        myCheckBox.Checked = true;
                    }
                }
            }
        }

        //This method is used to save the checkedstate of values
        private void SaveCheckedValues()
        {
            var checkedIds = new List<string>();

            foreach (GridViewRow gvrow in gvTutorList.Rows)
            {
                string index = gvTutorList.DataKeys[gvrow.RowIndex].Value.ToString();
                bool result = ((CheckBox)gvrow.FindControl("cbSelect")).Checked;

                // Check in the Session
                if (Session["CHECKED_ITEMS"] != null)
                {
                    checkedIds = (List<string>)Session["CHECKED_ITEMS"];
                }
                if (result)
                {
                    if (!checkedIds.Contains(index))
                    {
                        checkedIds.Add(index);
                    }
                }
                else
                {
                    checkedIds.Remove(index);
                }
            }
            if (checkedIds != null && checkedIds.Count > 0)
            {
                Session["CHECKED_ITEMS"] = checkedIds;
            }
        }

        protected void btBack_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("Group.aspx");
        }
    }
}